package org.springframework.boot.jdbc;

import java.sql.Connection;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.boot.jdbc.AbstractDataSourceInitializer;
import org.springframework.boot.jdbc.DataSourceInitializationMode;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceUtils;

public abstract class AbstractBaseDataSourceInitializer extends AbstractDataSourceInitializer {
	
	private boolean isCreated = false;

	protected AbstractBaseDataSourceInitializer(DataSource dataSource, ResourceLoader resourceLoader) {
		super(dataSource, resourceLoader);
		try {
			Connection connection = DataSourceUtils.getConnection(dataSource);
			try {
				// 自建的表
				Statement stmt = connection.createStatement();
				stmt.execute(getValidSql());
				isCreated = true;
			} catch (Exception e) {
				isCreated = false;
			} finally {
				DataSourceUtils.releaseConnection(connection, dataSource);
			}
		} catch (Exception e) {
		}
	}

	@Override
	protected DataSourceInitializationMode getMode() {
		if (isCreated) {
			return DataSourceInitializationMode.NEVER;
		}
		return DataSourceInitializationMode.ALWAYS;
	}

	protected abstract String getValidSql() ;
}
